//
//  MCWarehouseRealtimeController.m
//  XTCloud
//
//  Created by QA on 2017/8/23.
//  Copyright © 2017年 ShangHai HaoLei Software Technology Co., Ltd. All rights reserved.
//

#import "MCWarehouseRealtimeController.h"

#import "MNReportView.h"
#import "UITableView+Custom.h"
#import "NSDictionary+DataFormat.h"
#import "NSString+handle.h"
#import "KWFormViewQuickBuilder.h"

#import "GEObjectValueTableViewCell.h"
#import "GEProgressBarTableViewCell.h"
#import "MCWarehouseListViewCell.h"

#import "WebServiceCommonRequest.h"

@interface MCWarehouseRealtimeController ()

@property (nonatomic,strong) NSMutableArray *valueData;
@property (assign, nonatomic) NSInteger segmentActionState;

@end

@implementation MCWarehouseRealtimeController
@synthesize tableView = _tableView;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        [self setTitle: @"材料库存"];
        [self addStationToNavigationItem];
    }
    return self;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self.segmentedView addTarget:self action:@selector(segmentAction:) forControlEvents:UIControlEventValueChanged];
    [self getNetWorkDataIsReresh];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

#pragma make - Station Notification

-(void)updateStationNotification:(ModuleAuthorityEntity*)model
{
    [self.valueData removeAllObjects];
    [self.tableView reloadData];
    [self getNetWorkDataIsReresh];
}

- (void)createIndicatorView
{
    CGFloat width = self.view.bounds.size.width;
    CGFloat height = self.view.bounds.size.height;
    
    UIButton *_promptButton = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, width, height)];
    [_promptButton setTitle:@"暂无报表数据" forState:UIControlStateNormal];
    [_promptButton setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    _promptButton.titleLabel.font = [UIFont systemFontOfSize:15];
    _promptButton.userInteractionEnabled = NO;
    [self.view addSubview:_promptButton];
}

//具体委托方法实例
-(void)segmentAction:(UISegmentedControl *)Seg
{
    NSInteger index = Seg.selectedSegmentIndex;
    self.segmentActionState = index;
    
    if (self.tableView.visibleCells.count > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
        [self.tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionTop];
        [self.tableView reloadData];
    }
}

#pragma mark 网络获取数据

- (void)getNetWorkDataIsReresh
{
    //显示进度条
    [self.tableView showCustomProgressOffset:130];
    
    WebServiceCommonRequest *content = [[WebServiceCommonRequest alloc] init];
    [content setInterfaceType:InterfaceTypeERP];
    [content setModuleType:@"YCL_SSKC_CHART"];
    [content setResultBackType:ResultBackTypeCommonUnordered];
    
    //设置站点ID
    StationInfoEntity *model = [[GetUserStationService sharedService] getSelectStationEntity];
    [content setStationID:[model.stationId integerValue]];
    
    [content startAsyncConnectCompleted:^(ServiceResultModel *result, NSDictionary *userInfo) {
        //添加数据，刷新页面
        if(result.resultArray && result.resultArray.count>1){
            NSArray *valueArray = result.resultArray;
            [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
            self.valueData = [NSMutableArray arrayWithArray:valueArray];
            [self.tableView reloadData];
            
            if(!(valueArray && valueArray.count > 0))
            [self.tableView setTableViewNotDataDrawText:@"暂无库存数据" isShow:YES];
            
        } else {
            [self.tableView setTableViewNotDataDrawText:@"暂无库存数据" isShow:YES];
        }
        
    } failed:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"哦，出错了"];
        
    } abnormal:^(NSError *error, NSDictionary *userInfo) {
        NSLog(@"=====%@",error);
        [self errorInfoViewText:@"无法连接网络"];
    }];
}

- (void)errorInfoViewText:(NSString*)label
{
    if (self.tableView.visibleCells.count <= 0) {
        [self.tableView setTableViewNotDataDrawText:label isShow:YES];
    } else {
        [self.tableView setTableViewNotDataDrawText:nil isShow:NO];
        [self showErrorHUDText:label];
    }
}

#pragma mark - reloadTable

- (KWFormView *)reloadTableCell:(GEObjectValueTableViewCell*)cell indexPath:(NSIndexPath *)indexPath
{
    NSArray *titles = @[@"仓储位置",@"品名",@"规格",@"最大数量",@"剩余数量"];
    
    KWFormViewQuickBuilder *builder = [[KWFormViewQuickBuilder alloc] init];
    [builder setBorderColor:[UIColor colorWithWhite:0.88 alpha:1.0]];
    [builder addRecord:titles];
    
    NSArray *arrayValue = [self.valueData objectAtIndex:indexPath.section + 1];
    for(NSDictionary *dic in arrayValue){
        NSString *ckwz = [dic objectFormatStringForKey:@"仓储位置" defaults:@"-"];
        NSString *pm = [dic objectFormatStringForKey:@"品名" defaults:@"-"];
        NSString *gg = [dic objectFormatStringForKey:@"规格" defaults:@"-"];
        NSString *zdsl = [dic objectFormatStringForKey:@"最大数量" defaults:@"-"];
        NSString *sysl = [dic objectFormatStringForKey:@"剩余数量" defaults:@"-"];
        [builder addRecord:@[ckwz,pm,gg,zdsl,sysl]];
    }
    
    CGFloat itemWidth = SuperWidth/32;
    NSNumber *value1 = [NSNumber numberWithFloat:(itemWidth*5)];
    NSNumber *value2 = [NSNumber numberWithFloat:(itemWidth*7)];
    NSNumber *value3 = [NSNumber numberWithFloat:(itemWidth*7)];
    NSNumber *value4 = [NSNumber numberWithFloat:(itemWidth*6.5)];
    NSNumber *value5 = [NSNumber numberWithFloat:(itemWidth*6.5)];
    
    KWFormView *formView = [builder startCreatWithWidths:@[value1,value2,value3,value4,value5] startPoint:CGPointMake(0, 0)];
    formView.mKWFormViewHeight = 22;
    return formView;
}

#pragma mark - reloadTable

- (void)addObjectToArray:(NSMutableArray*)array ins:(NSInteger)way value:(id)object
{
    if (way >= array.count) { //添加
        [array addObject:object];
    } else { //替换
        [array setObject:object atIndexedSubscript:way];
    }
}

#pragma mark
#pragma mark - UITableViewDataSource

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    NSArray *arrayValue = [self.valueData firstObject];
    return arrayValue.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if (self.segmentActionState == 0) {
        NSArray *arrayValue = [self.valueData objectAtIndex:section + 1];
        return arrayValue.count;
    } else {
        return 1;
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(self.segmentActionState == 0){
        return [self drawChartTableListView:tableView cellForRowAtIndexPath:indexPath];
    } else {
        return [self drawChartTableView:tableView cellForRowAtIndexPath:indexPath];
    }
}

- (UITableViewCell *)drawChartTableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [NSString stringWithFormat:@"GEObjectValueTableViewCellGBTV%ld",(long)indexPath.section];
    GEObjectValueTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[GEObjectValueTableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
        //添加图表
        KWFormView *formView = [self reloadTableCell:cell indexPath:indexPath];
        [cell.contentView addSubview:formView];
    }
    return cell;
}

- (UITableViewCell *)drawChartTableListView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    NSString *identifier = [NSString stringWithFormat:@"MCWarehouseListViewCell%ld",(long)indexPath.section];
    MCWarehouseListViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MCWarehouseListViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        cell.selectionStyle = UITableViewCellSelectionStyleNone;
    }
    
    NSArray *arrayValue = [self.valueData objectAtIndex:indexPath.section + 1];
    NSDictionary *mDictionary = [arrayValue objectAtIndex:indexPath.row];
    
    if (indexPath.row >= arrayValue.count - 1)
        cell.lineView.hidden = YES;
    else cell.lineView.hidden = NO;
    
    CGFloat maxValue = [mDictionary objectFormatFloatForKey:@"最大数量"];
    maxValue = (maxValue <= 0) ? 1 : maxValue;
    
    CGFloat syValue = [mDictionary objectFormatFloatForKey:@"剩余数量"];
    NSString *pm = [mDictionary objectFormatStringForKey:@"品名" defaults:@"无品名"];
    NSString *gg = [mDictionary objectFormatStringForKey:@"规格" defaults:@"无规格"];
    CGFloat valueBFB = syValue/maxValue*100;
    
    cell.infoLabel.text = [NSString stringWithFormat:@"%@[%@]  %0.1f%%",pm,gg,valueBFB];
    cell.progressLabel.progress = syValue/maxValue;
    cell.maxLabel.text = [mDictionary objectFormatStringForKey:@"最大数量" format:@"总量%@" defaults:@"总量0"];
    cell.syLabel.text = [mDictionary objectFormatStringForKey:@"剩余数量" format:@"剩余%@" defaults:@"剩余0"];
    cell.ckLabel.text = [mDictionary objectFormatStringForKey:@"仓储位置" defaults:@"未知"];
    
    //进度条颜色配置
    if(valueBFB >= 70.0f){
        cell.progressLabel.progressTintColor = [UIColor colorWithRed:50/255.0 green:205/255.0 blue:50/255.0 alpha:0.9];
    } else if(valueBFB >= 20.0f){
        cell.progressLabel.progressTintColor = [UIColor colorWithRed:254/255.0 green:187/255.0 blue:8/255.0 alpha:0.9];
    } else if(valueBFB < 20.0f){
        //cell.progressLabel.progressTintColor = [UIColor colorWithRed:254/255.0 green:0/255.0 blue:0/255.0 alpha:1];
        cell.progressLabel.progressTintColor = [UIColor colorWithRed:245.0 / 255.0 green:94.0 / 255.0 blue:78.0 / 255.0 alpha:0.9f];
    }
    
    return cell;
}

#pragma mark
#pragma mark - UITableViewDelegate

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SuperWidth, 30)];
    view.backgroundColor = [UIColor whiteColor];
    
    UILabel *lable = [[UILabel alloc] initWithFrame:CGRectMake(5, 0, SuperWidth - 10, 29.5)];
    lable.textColor = [UIColor darkGrayColor];
    lable.textColor = ThemeColorBlue;
    //lable.textColor = [UIColor colorWithWhite:0.33 alpha:1.0];
    lable.font = [UIFont boldSystemFontOfSize:15];
    [view addSubview:lable];
    
    NSArray *arrayValue = [self.valueData firstObject];
    NSDictionary *qddjDic = [arrayValue objectAtIndex:section];
    NSString *title = [NSString stringWithFormat:@"%@当前库存(吨)",[qddjDic objectFormatStringForKey:@"生产线"]];
    lable.text = title;
    
    UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 29.5, SuperWidth, 0.5)];
    lineView.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.1];
    [view addSubview:lineView];
    
    return view;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (self.segmentActionState == 0) {
        return 60;
    } else {
        KWFormView *formView = [self reloadTableCell:nil indexPath:indexPath];
        return [formView getFormViewHeight] + 1;
    }
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
}

@end
